<?php

use App\Admin\Controller\Base\RouteController;
use App\Admin\Service\Base\RouteService;
use App\Common\Enums\Base\RouteEnumType;
use App\Common\Util\TP;
use Sc\Util\HtmlStructure\Form;
use Sc\Util\HtmlStructure\Form\FormItem;
use Sc\Util\HtmlStructure\Html\Html;
use Sc\Util\HtmlStructure\Html\Js\JsFunc;

Html::create('添加路由');
$allRoute = array_column(TP::route()->getRouteList(), 'rule');
$allRoute = array_unique(array_filter($allRoute, fn($v) => preg_match('/^[\w\-\/]+$/', $v)));
$allRoute = array_map(fn($v) => ['value' => trim($v)], array_values($allRoute));

$form = Form::create('routeForm')->config('label-width', '80px');
$menu = RouteService::aop()->getMenu();

$routeDefault = '';
if (TP::request()->get('route')) {
    $routeDefault = TP::request()->get('route') . '?_tab=1&id=' . TP::request()->get('_id');
}

$form->addFormItems(
    FormItem::hidden('id'),
    FormItem::text('title', '标题'),
    FormItem::cascader('pid','上级')->options($menu)->setVAttrs([
        ':props'    => "pidProps",
        'clearable' => '',
        'ref'       => 'rpid',
    ])->event('change', JsFunc::anonymous()->code('this.$refs["rpid"].togglePopperVisible(false)')),
    FormItem::radio('type', '类型')->options(RouteEnumType::mapping())->default(RouteEnumType::LeftMenu),
    FormItem::text('route', '路由')->options($allRoute)->default($routeDefault),
    FormItem::icon('icon', '图标')->default(''),
    FormItem::text('weigh', '权重')->default(1),

    TP::request()->get('_id')
        ? FormItem::submit()->successClose('parent')->submitUrl(
            TP::route()->to([RouteController::class, 'create'])->url(),
            TP::route()->to([RouteController::class, 'update'])->url(),
        )->success(sprintf("parent.VueApp.%sGetData()", TP::request()->get('tag')))
        : FormItem::submit()->successClose('current')->submitUrl(
            TP::route()->to([RouteController::class, 'create'])->url(),
            TP::route()->to([RouteController::class, 'update'])->url(),
        )->success('VueApp.routeGetData()')
);

Html::js()->vue->set('pidProps', [
    'value'         => 'index',
    'label'         => 'title',
    'checkStrictly' => true,
    'emitPath'      => false
]);

return $form->render();